package com.yonyou.pmclouds.basecom.error;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.BusinessRuntimeException;
import com.yonyou.pmclouds.basecom.exception.IBusinessFeature;
import com.yonyou.pmclouds.basecom.view.BuziExWrapObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 默认的controller的异常处理类，公共的异常处理，请放置在这里
 *
 * @author mapeif
 */
@ControllerAdvice(basePackages = "com.yonyou.pmclouds")
@Slf4j
public class DefaultExceptionHandler {

    @ExceptionHandler({BusinessException.class, BusinessRuntimeException.class})
    @ResponseBody
    public BuziExWrapObject defaultBusiExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        return getWrapped(ex);
    }

    @ExceptionHandler({UnauthorizedException.class})
    @ResponseBody
    public BuziExWrapObject UnauthorizedExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        BuziExWrapObject wrapObject = new BuziExWrapObject();
        wrapObject.setExMsg("没有该资源的访问权限");
        return wrapObject;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public BuziExWrapObject defaultExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        BuziExWrapObject wrapObject = new BuziExWrapObject();
        //TODO 解析dubbo的字符行异常
        wrapObject.setExMsg("系统内部发生未知错误，请稍后重试！");
        return wrapObject;
    }

    private BuziExWrapObject getWrapped(Exception ex) {
        BuziExWrapObject wrapObject = new BuziExWrapObject(ex.getMessage());
        IBusinessFeature info = (IBusinessFeature) ex;
        wrapObject.setExCode(info.getExCode());
        wrapObject.setAdditionInfo(info.getAddition());
        return wrapObject;
    }
}
